import React from 'react'
import menuRoute from 'routes/menuRoute'
import moment from 'moment'
import { deepCopy , messages } from "share/common";
import { connect } from 'react-redux'
import {Form, Steps, Card, InputNumber, DatePicker, Divider, Icon, Popover, Checkbox, Button, Row, Col, Spin, Modal,
  Select} from 'antd';
const Step = Steps.Step;
const FormItem = Form.Item;
const { Option } = Select;
import 'styles/senior-service-open/order-confirm.scss'
import seniorService from 'containers/increment-service/senior-service-open/senior-service.service'

class OrderConfirm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      loadingBtn: false,
      showDetailPage: false,
      orderID: null,
      buyCount: 1, //购买数量
      buyTime: 1, //购买时长
      effectiveDate: moment(new Date()).format('YYYY-MM-DD'), //服务生效日期
      deadline: undefined, //服务到期日期
      upperLimit: null, //使用上限
      submitDisabled: true, //确认订单按钮
      serviceInfo: {},
      orderInfo: {},
      totalAmount: 0,
      actualAmount: 0,
      orderStatus: {
        WAIT_PAYMENT: messages('senior-service-open.key34')/*待付款*/,
        PAID: messages('senior-service-open.key35')/*已付款*/,
        CLOSED: messages('senior-service-open.key36')/*已关闭*/
      },
      orderType: {
        NEW_BUY: messages('senior-service-open.key37')/*新购*/,
        ADD_BUY: messages('senior-service-open.key38')/*加购*/,
        RENEWAL: messages('senior-service-open.key39')/*续费*/
      },
      serviceList: menuRoute.getRouteItem('senior-service-open'), //服务列表页面
      orderPay: menuRoute.getRouteItem('order-pay'), //付款页面
      serviceBank: [],
      GRADIENT: {upperLimit: ""},
      chargeStrategyDetails: [],
    }
  }

  componentDidMount() {
    this.getInfo();
    this.getServiceBank();
  }

  getInfo = () => {
    this.setState({ loading: true });
    seniorService.getServiceDetail(this.props.params.id).then(res => {
      if (res.data.chargeMode === "GRADIENT") {
        let buyCount = res.data.minCount;
        let upperLimit = "";
        this.setState({chargeStrategyDetails: res.data.chargeStrategyDetails})
        res.data.chargeStrategyDetails.map(item => {
          if(item.maxCount){
            if((item.minCount <= buyCount) && (buyCount <= item.maxCount)){
              upperLimit = item.upperLimit * buyCount;
              this.setState({ GRADIENT: {upperLimit: item.upperLimit}, upperLimit })
            }
          }else{
            if(item.minCount <= buyCount){
              upperLimit = item.upperLimit * buyCount;
              this.setState({ GRADIENT: {upperLimit: item.upperLimit}, upperLimit })
            }
          }
        })
      }else{
        this.setState({upperLimit: res.data.upperLimit})
      }
      this.setState({
        loading: false,
        serviceInfo: res.data,
        buyCount: res.data.minCount || 1,
        buyTime: res.data.minTime || 1,
      }, () => {
        const { effectiveDate, buyTime, buyCount } = this.state;
        this.calcDeadline(effectiveDate, buyTime);
        this.calcAmount(buyCount, buyTime)
      })
    }).catch(err => {
      this.setState({ loading: false });
    })
  };

  getServiceBank = () => {
    seniorService.getServiceBank()
      .then(res => {
        if(res && res.data) {
          this.setState({
            serviceBank: res.data.BANK,
          });
        }
      })
      .catch(err => {

      });
  };

  //禁用选择的服务生效时间
  disabledDate = (current) => {
    let dateRange = 3650; //可修改当天之后E天内的日期（E先系统级别设定为300天）
    let disabled = false;
    let startDate = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);
    let endDate = new Date(new Date().getTime() + dateRange * 24 * 60 * 60 * 1000);
    if (current < moment(startDate) || current > moment(endDate)) {
      disabled = true;
    }
    return current && disabled
  };

  //修改购买数量
  handleCountChange = (value) => {
    if (!(isNaN(value) || String(value).indexOf('.') !== -1)) {
      this.setState({ buyCount: value });
      this.calcUpperLimit(value, this.state.buyTime);
      this.calcAmount(value, this.state.buyTime)
    }
  };

  //修改购买时长
  handleDurationChange = (value) => {
    const {effectiveDate, buyCount} = this.state;
    if (!(isNaN(value) || String(value).indexOf('.') !== -1)) {
      this.setState({buyTime: value});
      this.calcDeadline(effectiveDate, value);
      this.calcUpperLimit(buyCount, value);
      this.calcAmount(buyCount, value)
    }
  };

  //修改服务生效时间
  handleEffectiveDateChange = (date, dateString) => {
    this.setState({ effectiveDate: dateString });
    this.calcDeadline(dateString, this.state.buyTime)
  };

  //计算服务到期时间
  calcDeadline = (startDate, buyTime) => {
    const { serviceInfo } = this.state;
    let addYear = 0;
    let addMonth = 0;
    if (startDate && buyTime) {
      if(serviceInfo.timeUnit === "MONTH"){
        addYear =parseInt(Number(buyTime) / 12);
        addMonth = Number(buyTime) % 12;
      }else if(serviceInfo.timeUnit === "YEAR"){
        addYear = Number(buyTime);
      }
      let year = new Date(startDate).getFullYear();
      let month = new Date(startDate).getMonth() + 1;
      let date = new Date(startDate).getDate();
      let deadlineYear = year + addYear;
      let deadlineMon = month + addMonth;
      let arr = [deadlineYear, deadlineMon, date];
      let deadline = arr.join("-");
      //如果服务生效日期是2月29，则判断到期时间的年份是否有29号
      if (month === 2 && date === 29) {
        if (!(deadlineYear % 4 === 0 && deadlineYear % 400 !== 0)) {
          deadline = deadline.replace(/-\d{2}/g, '-01').replace(/-\d{2}-/, '-03-');
        }
      }
      this.setState({ deadline })
    } else {
      this.setState({ deadline: undefined })
    }
  };

  //计算使用上限
  calcUpperLimit = (buyCount, buyTime) => {
    const { serviceInfo, chargeStrategyDetails } = this.state;
    if (serviceInfo.priceMode === 1001) {
      let upperLimit = serviceInfo.upperLimit * buyCount * buyTime;
      this.setState({ upperLimit })
    }
    if (serviceInfo.chargeMode === "GRADIENT") {
      let upperLimit = "";
      let arr = serviceInfo.chargeStrategyDetails || chargeStrategyDetails;
      arr.map(item => {
        if(item.maxCount){
          if((item.minCount <= buyCount) && (buyCount <= item.maxCount)){
            upperLimit = item.upperLimit * buyCount;
            this.setState({ GRADIENT: {upperLimit: item.upperLimit}, upperLimit })
          }
        }else{
          if(item.minCount <= buyCount){
            upperLimit = item.upperLimit * buyCount;
            this.setState({ GRADIENT: {upperLimit: item.upperLimit}, upperLimit })
          }
        }
      })
    }
  };

  //计算金额
  calcAmount = (buyCount, buyTime) => {
    let serviceInfo = this.state.serviceInfo;
    let totalAmount, actualAmount, price = serviceInfo.price;
    if(serviceInfo.serviceTypeCode === "OCR"){
      totalAmount = price * buyCount;
      actualAmount = price * buyCount;
    }
    if(serviceInfo.serviceTypeCode === "BWE"){
      totalAmount = price * buyCount * buyTime;
      actualAmount = price * buyCount * buyTime;
    }
    switch(serviceInfo.priceMode) {
      case 1001: //人*月(年)
        totalAmount = price * buyCount * buyTime;
        actualAmount = price * buyCount * buyTime;
        break;
      case 1002: //张
        totalAmount = price * buyCount;
        actualAmount = price * buyCount;
        break;
      case 1003: //月(年)
        totalAmount = price * buyTime;
        actualAmount = price * buyTime;
        break;
      case 1004: //一次性付款
        totalAmount = price;
        actualAmount = price;
    }
    this.setState({ totalAmount, actualAmount })
  };

  //提交订单
  handleSubmitOrder = (e) => {
    const { serviceInfo, effectiveDate, deadline, buyCount, buyTime, totalAmount, actualAmount, upperLimit, orderID}
    = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let params = deepCopy(serviceInfo);
        if(serviceInfo.priceMode === 1001 || serviceInfo.priceMode === 1003) {
          if(deadline === undefined){
            params.expireDate = null;
          }else{
            let a = deadline.split('-');
            let currentTime = moment(new Date(a[0], parseInt(a[1]) - 1, a[2]));
            params.expireDate = moment(currentTime).utc().format();
          }
        }else{
          delete params.expireDate;
        }
        params.chargeStrategyId = this.props.params.id;
        params.serviceName = params.name;
        params.serviceCode = params.code;
        params.serviceUpperLimit = params.upperLimit;
        params.orderType = 'NEW_BUY'; //NEW_BUY 新购 / ADD_BUY 加购 / RENEWAL 续费
        params.buyCount = buyCount;
        params.buyTimeCount = buyTime;
        params.totalAmount = totalAmount;
        params.discountAmount = 0; //优惠 金额本期不做
        params.actualAmount = actualAmount;
        params.effectiveDate = moment(effectiveDate).utc().format();
        params.upperLimit = upperLimit;
        params.bankName = values.bankName;
        delete params.id;
        orderID && (params.id = orderID);
        delete params.createdDate;
        this.setState({ loadingBtn: true });
        seniorService.createOrder(params).then(res => {
          this.setState({
            serviceInfo: res.data,
            orderInfo: res.data,
            orderID: res.data.id,
            loadingBtn: false,
            showDetailPage: true
          })
        }).catch(err => {
          this.setState({
            loadingBtn: false,
          })
        })
      }
    })
  };

  //上一步
  goBack = () => {
    this.context.router.push(this.state.serviceList.url)
  };

  //去付款
  toPay = () => {
    this.context.router.push(this.state.orderPay.url.replace(':orderId', this.state.orderID))
  };

  renderDetailItem = (title, value) => {
    return (
      <Row>
        <Col span={8}>{title}：</Col>
        <Col span={16} style={{whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          <Popover content={value}
                   placement="topLeft"
                   overlayStyle={{maxWidth: 500}}>
            {value}
          </Popover>
        </Col>
      </Row>
    )
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loading, loadingBtn, deadline, submitDisabled, showDetailPage, serviceInfo, orderInfo, totalAmount,
      actualAmount, upperLimit, orderStatus, GRADIENT, serviceBank } = this.state;
    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 10, offset: 1}
    };
    let effectiveDate = moment(orderInfo.effectiveDate).format('YYYY/MM/DD');
    let expireDate = moment(orderInfo.expireDate).format('YYYY/MM/DD');

    return (
      <div className="order-confirm">
        <Steps current={1} size="small">
          <Step title={messages('senior-service-open.key2')/*选择服务*/} />
          <Step title={messages('senior-service-open.key3')/*确认订单*/} />
          <Step title={messages('senior-service-open.key4')/*付款*/} />
          <Step title={messages('senior-service-open.key5')/*申请开票*/} />
          <Step title={messages('senior-service-open.key6')/*开通设置*/} />
        </Steps>
        <Spin spinning={loading}>
          {!showDetailPage ? (
            <div>
              <Card title={messages('senior-service-open.key40')/*服务信息*/} bordered={false} className="info-container">
                <div className="info-title">
                  {serviceInfo.name || serviceInfo.serviceName}：
                  <span className="price">{serviceInfo.price}</span>{messages('senior-service-open.key41')/*元*/}
                  {serviceInfo.countUnitName ? `/${serviceInfo.countUnitName}` : ''}
                  {serviceInfo.timeUnitName ? `/${serviceInfo.timeUnitName}` : ''}
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {messages('senior-service-open.key42')/*服务编码*/}：{serviceInfo.code}
                </div>
                <div className="info-content">{serviceInfo.intro}</div>
              </Card>
              <Card title={messages('senior-service-open.key43')/*相关设置*/} bordered={false} className="setting-container">
                <Form>
                  {/*priceMode 价格模式 1001 人*月(年), 1002 张, 1003 月(年), 1004 一次性付款*/}
                  {
                    serviceInfo.serviceTypeCode === "OCR" && (
                      <FormItem {...formItemLayout} label={messages('senior-service-open.key44')/*购买数量*/}>
                        {getFieldDecorator('buyCount',{
                          rules: [{
                            required: true,
                            message: messages('senior-service-open.key45')/*请填写*/
                          }],
                          initialValue: serviceInfo.buyCount || serviceInfo.minCount || 1
                        })(
                          <InputNumber precision={0} min={serviceInfo.minCount} onChange={this.handleCountChange}/>
                        )}
                        {serviceInfo.countUnitName}
                      </FormItem>
                    )
                  }
                  {serviceInfo.priceMode !== 1004  && (
                    <div>
                      {(serviceInfo.priceMode === 1001 || serviceInfo.priceMode === 1002 || serviceInfo.serviceTypeCode === "BWE" )
                      && (
                        <FormItem {...formItemLayout} label={messages('senior-service-open.key44')/*购买数量*/}>
                          {getFieldDecorator('buyCount',{
                            rules: [{
                              required: true,
                              message: messages('senior-service-open.key45')/*请填写*/
                            }],
                            initialValue: serviceInfo.buyCount || serviceInfo.minCount || 1
                          })(
                            <InputNumber precision={0} min={serviceInfo.minCount} onChange={this.handleCountChange}/>
                          )}
                          {serviceInfo.countUnitName}
                        </FormItem>
                      )}
                      {(serviceInfo.priceMode === 1001 || serviceInfo.priceMode === 1003 || serviceInfo.serviceTypeCode === "BWE" )
                      && (
                        <FormItem {...formItemLayout} label={messages('senior-service-open.key46')/*购买时长*/}>
                          {getFieldDecorator('buyTimeCount',{
                            rules: [{
                              required: true,
                              message: messages('senior-service-open.key45')/*请填写*/
                            }],
                            initialValue: serviceInfo.buyTimeCount || serviceInfo.minTime || 1
                          })(
                            <InputNumber precision={0} min={serviceInfo.minTime} onChange={this.handleDurationChange}/>
                          )}
                          {serviceInfo.timeUnitName}
                        </FormItem>
                      )}
                      {
                        serviceInfo.serviceTypeCode === "BWE" &&
                          <FormItem  {...formItemLayout} label={messages('increment-service.key20')/*购买服务银行*/}>
                            {getFieldDecorator('bankName', {
                              rules: [{
                                required: true,
                                message: messages('senior-service-open.key45')/*请填写*/
                              }],
                              initialValue: serviceInfo.bankName
                            })(
                              <Select placeholder={messages('common.select')/*请选择*/}
                                      allowClear
                                      showSearch
                                      style={{width: 300}}
                                      filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                              >
                                {serviceBank.length && serviceBank.map(option => {
                                  return <Option key={option.name}>{option.name}</Option>
                                })}
                              </Select>
                            )}
                          </FormItem>
                      }
                        <FormItem {...formItemLayout} label={messages('senior-service-open.key47')/*选择服务生效时间*/}>
                          {getFieldDecorator('effectiveDate',{
                            rules: [{
                              required: true,
                              message: messages('common.select')/*请选择*/
                            }],
                            initialValue: orderInfo.effectiveDate ? moment(orderInfo.effectiveDate) :
                              (serviceInfo.effectiveDate ? moment(serviceInfo.effectiveDate): moment(new Date()))
                          })(
                            <DatePicker allowClear={false}
                                        disabledDate={this.disabledDate}
                                        onChange={this.handleEffectiveDateChange}
                            />
                          )}
                          <Popover content={messages('senior-service-open.key48')/*服务实际生效日期将取MAX（【已付款日期】，【服务生效日期】）*/}
                                   overlayStyle={{maxWidth: 500}}>
                            <Icon type="info-circle" className="valid-date-info" />
                          </Popover>
                        </FormItem>
                      {(serviceInfo.priceMode === 1001 || serviceInfo.priceMode === 1003 || serviceInfo.serviceTypeCode === "BWE" )
                      && (
                        <FormItem {...formItemLayout} label={messages('senior-service-open.key49')/*服务到期时间*/}>
                          {deadline}
                        </FormItem>
                      )}
                      {
                        upperLimit &&
                        <FormItem {...formItemLayout} label={messages('senior-service-open.key50')/*使用上限*/}>
                          {
                            serviceInfo.chargeMode === "GRADIENT" ?
                              <span>
                                {GRADIENT.upperLimit}&nbsp;{messages('senior-service-open.key51')/*张*/}/{messages('increment-service.key19')/*份*/}&nbsp;
                                *&nbsp;{this.props.form.getFieldValue("buyCount")}{messages('increment-service.key19')/*份*/}&nbsp;=&nbsp;
                                {upperLimit}{messages('senior-service-open.key51')/*张*/}
                              </span>
                              : <span>{upperLimit}{messages('senior-service-open.key51')/*张*/}</span>
                          }
                        </FormItem>
                      }
                      <Divider/>
                    </div>
                  )}
                  <FormItem {...formItemLayout} label={messages('senior-service-open.key52')/*订单金额*/}>
                    <span className="price-color">{this.filterMoney(totalAmount)}</span>{messages('senior-service-open.key41')/*元*/}
                  </FormItem>
                  {/*优惠金额本期不做*/}
                  {
                    false &&
                    <FormItem {...formItemLayout} label={messages('senior-service-open.key53')/*优惠金额*/}>
                      <span className="price-color">{this.filterMoney(0)}</span>{messages('senior-service-open.key41')/*元*/}
                      {/*（平台优惠：<span className="price-color">7折</span>）*/}
                    </FormItem>
                  }
                  <FormItem {...formItemLayout} label={messages('senior-service-open.key54')/*实需支付*/}>
                    <span className="price-color actual-price">{this.filterMoney(actualAmount)}</span>{messages('senior-service-open.key41')/*元*/}
                  </FormItem>
                  <div className="btn-container">
                    <div>
                      <Checkbox onChange={e => this.setState({submitDisabled: !e.target.checked})}/>
                      {
                        serviceInfo.serviceTypeCode === "OCR" ?
                          <a target="_blank" href="https://console.huilianyi.com/register/pages/ocr_protocol.html">
                            {messages('senior-service-open.key55')/*我已阅读并同意签署《服务协议》*/}
                          </a>
                          :
                          (
                            serviceInfo.serviceTypeCode === "BWE" ?
                              <a target="_blank" href="https://console.huilianyi.com/register/pages/payment_protocol.html">
                                {messages('senior-service-open.key55')/*我已阅读并同意签署《服务协议》*/}
                              </a>
                          :
                          <a target="_blank" href="https://console.huilianyi.com/register/pages/inv_vertify_protocol.html">
                            {messages('senior-service-open.key55')/*我已阅读并同意签署《服务协议》*/}
                          </a>
                        )
                      }
                    </div>
                    <div>
                      <Button className="btn-last-step" onClick={this.goBack}>{messages('senior-service-open.key56')/*上一步*/}</Button>
                      <Button type="primary"  onClick={this.handleSubmitOrder} disabled={submitDisabled} loading={loadingBtn}>{messages('senior-service-open.key3')/*确认订单*/}</Button>
                    </div>
                  </div>
                </Form>
              </Card>
            </div>
          ) : (
            <div className="order-detail-show">
              <Card title={messages('senior-service-open.key57')/*订单详情*/} bordered={false} className="info-container">
                <Row className="info-row">
                  <Col span={8}>{this.renderDetailItem(messages('senior-service-open.key7')/*订单编号*/, orderInfo.orderCode)}</Col>
                  <Col span={8}>{this.renderDetailItem(messages('senior-service-open.key58')/*订单状态*/, orderStatus[orderInfo.status])}</Col>
                  <Col span={8}>{this.renderDetailItem(messages('senior-service-open.key59')/*订单类型*/, messages('loan-billing.key20')/*线上*/)}</Col>
                </Row>
                <Row className="info-row">
                  <Col span={8}>
                    {this.renderDetailItem(messages('senior-service-open.key60')/*服务名称*/, orderInfo.serviceName)}
                  </Col>
                  <Col span={8}>{this.renderDetailItem(messages('senior-service-open.key42')/*服务编码*/, orderInfo.serviceCode)}</Col>
                  {
                    serviceInfo.bankName &&
                    <Col span={8}>{this.renderDetailItem(messages('increment-service.key20')/*购买服务银行*/, orderInfo.bankName)}</Col>
                  }
                  {
                    serviceInfo.serviceTypeCode === "CHECK_INVOICE" && (serviceInfo.priceMode === 1001 || serviceInfo.priceMode === 1003) &&
                    <Col span={8}>{this.renderDetailItem(messages('senior-service-open.key61')/*服务期限*/, effectiveDate + ' - ' + expireDate)}</Col>
                  }
                  {
                    serviceInfo.countUnitName &&
                    <Col span={8}>{this.renderDetailItem(messages('senior-service-open.key62')/*法人数量*/, orderInfo.buyCount + serviceInfo.countUnitName)}</Col>
                  }
                  {
                    serviceInfo.timeUnitName &&
                    <Col span={8}>{this.renderDetailItem(messages('senior-service-open.key46')/*购买时长*/, orderInfo.buyTimeCount + serviceInfo.timeUnitName)}</Col>
                  }
                  {
                    orderInfo.upperLimit &&
                    <Col span={8}>{this.renderDetailItem(messages('senior-service-open.key50')/*使用上限*/, orderInfo.upperLimit + messages('senior-service-open.key51')/*张*/)}</Col>
                  }
                </Row>
                <Divider/>
                <Row className="info-row">
                  <Col span={3}>{messages('senior-service-open.key52')/*订单金额*/}：</Col>
                  <Col span={5}><span className="price-color">{this.filterMoney(orderInfo.totalAmount)}</span>{messages('senior-service-open.key41')/*元*/}</Col>
                </Row>
                <Row className="info-row">
                  <Col span={3}>{messages('senior-service-open.key53')/*优惠金额*/}：</Col>
                  <Col span={5}>
                    <span className="price-color">{this.filterMoney(orderInfo.discountAmount)}</span>{messages('senior-service-open.key41')/*元*/}
                    {/*（平台优惠：<span className="price-color">7折</span>）*/}
                  </Col>
                </Row>
                <Row className="info-row">
                  <Col span={3}>{messages('senior-service-open.key54')/*实需支付*/}：</Col>
                  <Col span={5}><span className="price-color actual-price">{this.filterMoney(orderInfo.actualAmount)}</span>{messages('senior-service-open.key41')/*元*/}</Col>
                </Row>
              </Card>
              <div className="btn-container">
                <Button className="btn-last-step"
                        onClick={() => this.setState({showDetailPage: false, submitDisabled: true})}>{messages('senior-service-open.key56')/*上一步*/}</Button>
                <Button type="primary" onClick={this.toPay}>{messages('senior-service-open.key63')/*去付款*/}</Button>
              </div>
            </div>
          )}
        </Spin>
        <Modal>
          <div>
          </div>
        </Modal>
      </div>
    )
  }
}

OrderConfirm.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
  }
}

const WrappedOrderConfirm = Form.create()(OrderConfirm);

export default connect(mapStateToProps)(WrappedOrderConfirm)
